package com.ideal.frame.util;

import cn.hutool.extra.ssh.Sftp;
import com.ideal.frame.config.SFtpProperties;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

@Slf4j
public class SFtpUtil {

    private String host;
    private int port;
    private String username;
    private String password;

    public SFtpUtil(SFtpProperties sFtpProperties) {
        this.host = sFtpProperties.getHost();
        this.port = sFtpProperties.getPort();
        this.username = sFtpProperties.getUsername();
        this.password = sFtpProperties.getPassword();
    }

    /**
     * 上传文件
     *
     * @param path 本地文件路径
     * @param tagPath 目标服务器路径
     * @return
     */
    public boolean upload(String path, String tagPath) {
        try(Sftp sftp = new Sftp(host, port, username, password)) {
            sftp.put(path, tagPath);
        } catch (Exception e) {
            log.error("sftp上传失败：{}", path, e);
            return false;
        }
        return true;
    }

    /**
     *
     * @param tagPath 目标服务器路径
     * @param input 上传文件流
     * @return
     */
    public boolean upload(String tagPath, InputStream input) {
        Sftp sftp = new Sftp(host, port, username, password);
        try {
            ChannelSftp client = sftp.getClient();
            client.put(input, tagPath);
        }  catch (SftpException e) {
            e.printStackTrace();
        } finally {
            sftp.close();
        }
        return true;
    }
}
